package linc.fun.openai.helper;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.base.Captcha;
import jakarta.annotation.Resource;
import linc.fun.openai.constants.CommonConstants;
import linc.fun.openai.domain.vo.CaptchaVO;
import linc.fun.openai.exception.BizException;
import linc.fun.openai.factory.CaptchaFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author yqlin
 * @date 2023/3/6 12:47
 * @description
 */
@Component
@Slf4j
public class CaptchaHelper {
    @Resource
    private CaptchaFactory captchaFactory;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public CaptchaVO generateCaptcha() {
        // 获取运算的结果
        Captcha captcha = captchaFactory.getCaptcha();
        String uuid = IdUtil.fastSimpleUUID();
        log.info("当前验证码code: {}, uuid: {}", captcha.text(), uuid);
        String codeKey = CommonConstants.CAPTCHA_CODE_KEY + uuid;
        stringRedisTemplate.opsForValue().setIfAbsent(codeKey, captcha.text(), captchaFactory.getCaptchaCode().getExpiration(), TimeUnit.MINUTES);
        return new CaptchaVO(uuid, captcha.toBase64());
    }

    public void verifyCaptcha(final String uuid, final String code) {
        // 验证码key
        String codeKey = CommonConstants.CAPTCHA_CODE_KEY + uuid;
        // 从redis中拿出结果信息
        String captcha = stringRedisTemplate.opsForValue().get(codeKey);
        //删除key
        stringRedisTemplate.delete(codeKey);
        // 判断验证码是否正确
        if (!Objects.equals(captcha, code)) {
            throw BizException.CAPTCHA_ERROR;
        }
    }
}
